package com.alibaba.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        // 返回类型
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        // 判断路径是否包含了login或者register
        if (uri.endsWith("login")||uri.endsWith("register")) {
            return false;
        }
        // 不包含就是需要登录的资源，所以需要请求访问
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取请求内容
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();

        // 获取响应内容
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");
        // 判断是否包含了token
        String token = request.getHeader("token");
        if (token.isEmpty()){
            try {
                PrintWriter writer = response.getWriter();
                Map<Object, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","登录失败，请重新登陆");;
                String jsonString = JSONObject.toJSONString(map);
                writer.write(jsonString);
                // 防止后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
        return null;
    }
}
